package com.manor.main.personalcenter;

import android.app.Dialog;
import android.os.Handler;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.manor.common.CommonAppConfig;
import com.manor.common.activity.AbsActivity;
import com.manor.common.bean.ConfigBean;
import com.manor.common.custom.SwitchButton;
import com.manor.common.http.CommonHttpConsts;
import com.manor.common.http.CommonHttpUtil;
import com.manor.common.interfaces.CommonCallback;
import com.manor.common.interfaces.ElvesPwdProvider;
import com.manor.common.utils.ActivityManager;
import com.manor.common.utils.DataCleanManager;
import com.manor.common.utils.DialogUitl;
import com.manor.common.utils.GlideCatchUtil;
import com.manor.common.utils.RouteUtil;
import com.manor.common.utils.SpUtil;
import com.manor.common.utils.SpUtils;
import com.manor.common.utils.StaIntentUtil;
import com.manor.common.utils.StringUtil;
import com.manor.common.utils.ToastUtil;
import com.manor.common.utils.VersionUtil;
import com.manor.common.utils.WordUtil;
import com.manor.im.utils.PushUtils;
import com.manor.main.R;
import com.manor.main.login.VCodeVerifyFragment;
import com.manor.main.utils.UpdateUtil;
import com.manor.main.utils.VersionManagementUtil;
import com.mob.adsdk.AdSdk;
import com.mob.gamesdk.GameSdk;
import com.tencent.qcloud.tim.uikit.TUIKit;
import com.tencent.qcloud.tim.uikit.base.IUIKitCallBack;
import com.umeng.analytics.MobclickAgent;

import java.io.File;

/**
 * 个人设置
 * Created by twq on 2020.3.26
 */
@Route(path = RouteUtil.PC_PERSONAL_SETTINGS)
public class PersonalSettingsActivity extends AbsActivity implements View.OnClickListener {
    private SwitchButton mSbSoundSwitch;
    private TextView mTvLogout;
    private SwitchButton sbSoundSwitch;
    private RelativeLayout rlLink;
    private LinearLayout rlUpdate;
    private TextView tvVersion;
    private LinearLayout rlClean;
    private TextView tvCache;
    private RelativeLayout rlChargeSet;
    private TextView tvLogout;
    private TextView tvNewVersion;
    private boolean mCloseChatMusic;//关闭聊天提示音
    private Handler mHandlerV;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_personal_settings;
    }


    @Override
    protected void main() {
        super.main();
        setTitle("设置");
        initView();
        initDate();
        checkVersion(false);
    }

    private void initDate() {
        //音效开关
        mCloseChatMusic = SpUtil.getInstance().getBooleanValue(SpUtil.CHAT_MUSIC_CLOSE);
        mSbSoundSwitch.setChecked(mCloseChatMusic);
        mSbSoundSwitch.setOnCheckedChangeListener(checkedChangeListener);
        tvVersion.setText(VersionUtil.getVersion());
        tvCache.setText(getCacheSize());
    }


    @Override
    protected void onDestroy() {
        if (mHandlerV != null) {
            mHandlerV.removeCallbacksAndMessages(null);
            mHandlerV = null;
        }
        CommonHttpUtil.cancel(CommonHttpConsts.GET_CONFIG);
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.rl_link) {//个人隐私
            RouteUtil.forwardPath(RouteUtil.PC_WEB, StaIntentUtil.PRIVACY_AGREEMENT);
        } else if (id == R.id.rl_update) {//检查更新
            checkVersion(true);
        } else if (id == R.id.rl_clean) {//清理缓存
            clearCache();
        } else if (id == R.id.rl_charge_set) {//设置交易密码
            ElvesPwdProvider provider = (ElvesPwdProvider) ARouter.getInstance()
                    .build(RouteUtil.ELVES_SET_PWD_PROVIDER)
                    .navigation();
            provider.showSetPwdDialog(this);
        } else if (id == R.id.rl_feed_back) {
            RouteUtil.forwardPcWeb("h5web/go/chc/sdfk.html?", StaIntentUtil.FEED_BACK);
        } else if (id == R.id.tv_logout) {//退出登录
            logout();
        } else if (id == R.id.rl_set_password) {
            String phone = SpUtil.getInstance().getStringValue(SpUtil.SP_MOBILE);
            ARouter.getInstance()
                    .build(RouteUtil.PATH_LOGIN)
                    .withInt(VCodeVerifyFragment.FLAG_FROM_TYPE, 3)
                    .withString(VCodeVerifyFragment.FLAG_TITLE_TEXT, "重置密码")
                    .withString(VCodeVerifyFragment.FLAG_BTN_TEXT, "完成")
                    .withString(VCodeVerifyFragment.FLAG_PHONE, phone)
                    .navigation();
        }
    }


    /**
     * 退出登录
     */
    private void logout() {
        SpUtils.getInstance(mContext).clear();
        SpUtil.getInstance().clear();
        CommonAppConfig.getInstance().clearLoginInfo();
        DataCleanManager.clearAllCache(this);
        //退出IM
        TUIKit.unInit();
        TUIKit.logout(new IUIKitCallBack() {
            @Override
            public void onSuccess(Object data) {
                TUIKit.unInit();
            }

            @Override
            public void onError(String module, int errCode, String errMsg) {

            }
        });
        PushUtils.deleteToken(mContext);
        //友盟统计登出
        MobclickAgent.onProfileSignOff();
        AdSdk.getInstance().setUserId(null);
        GameSdk.getInstance().setUserId(null);
        ActivityManager.getInstance().finishOtherActivities(PersonalSettingsActivity.class, false);
        ARouter.getInstance().build(RouteUtil.PATH_LAUNCHER)
                .navigation();

        finish();
    }


    /**
     * 获取缓存
     */
    private String getCacheSize() {
        try {
            return DataCleanManager.getTotalCacheSize(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "0.0KB";
    }

    /**
     * 清除缓存
     */
    private void clearCache() {
        final Dialog dialog = DialogUitl.loadingDialog(mContext, getString(R.string.setting_clear_cache_ing));
        dialog.show();
        DataCleanManager.clearAllCache(this);
        GlideCatchUtil.getInstance().clearImageAllCache();
        File gifGiftDir = new File(CommonAppConfig.GIF_PATH);
        if (gifGiftDir.exists() && gifGiftDir.length() > 0) {
            gifGiftDir.delete();
        }
        if (mHandlerV == null) {
            mHandlerV = new Handler();
        }
        mHandlerV.postDelayed(() -> {
            if (dialog != null) {
                dialog.dismiss();
            }
            if (tvCache != null) {
                tvCache.setText(getCacheSize());
            }
            ToastUtil.show(R.string.setting_clear_cache);
        }, 2000);
    }


    /**
     * 私信聊天提示音开关
     */
    private void toggleChatMusic() {
        mCloseChatMusic = !mCloseChatMusic;
        SpUtil.getInstance().setBooleanValue(SpUtil.CHAT_MUSIC_CLOSE, mCloseChatMusic);
    }

    /**
     * 检查更新
     */
    private void checkVersion(boolean isUpdate) {
        CommonAppConfig.getInstance().getConfig(new CommonCallback<ConfigBean>() {
            @Override
            public void callback(ConfigBean configBean) {
                if (configBean != null) {
                    if (StringUtil.isEmpty(configBean.getVersion())) {
                        return;
                    }
                    if (VersionManagementUtil.VersionComparison(configBean.getVersion(),
                            VersionManagementUtil.getVersion(mContext)) == 1) {
                        tvNewVersion.setVisibility(View.VISIBLE);
                        if (isUpdate) {
                            //                        VersionUtil.showDialog(mContext, configBean.getUpdateDes(), configBean.getDownloadApkUrl());
                            String title = WordUtil.getString(com.manor.common.R.string.version_update);
                            String content = configBean.getUpdateDes();
                            String apkUrl = configBean.getUpdateUrl();
                            int versionCode = configBean.getCurVersionCode();
                            boolean isForce = configBean.getIsForce().trim().equals("1");
                            String upType = "1";
                            String patchUrl = StringUtil.isNotEmpty(configBean.getPatchUrl()) ? configBean.getUpType() : "";

                            UpdateUtil.instance.initDownload(mContext, title, content, apkUrl, versionCode, isForce,
                                    upType, patchUrl);
                        }
                    } else {
                        tvNewVersion.setVisibility(View.INVISIBLE);
                        if (isUpdate)
                            ToastUtil.show(R.string.version_latest);
                    }
                }
            }
        });

    }

    private final SwitchButton.OnCheckedChangeListener checkedChangeListener = new SwitchButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(SwitchButton view, boolean isChecked) {
            toggleChatMusic();
        }
    };


    private void initView() {
        mSbSoundSwitch = findViewById(R.id.sb_sound_switch);
        tvNewVersion = findViewById(R.id.tvNewVersion);
        mTvLogout = findViewById(R.id.tv_logout);
        mTvLogout.setOnClickListener(this);
        sbSoundSwitch = findViewById(R.id.sb_sound_switch);
        rlLink = findViewById(R.id.rl_link);
        rlUpdate = findViewById(R.id.rl_update);
        tvVersion = findViewById(R.id.tv_version);
        rlClean = findViewById(R.id.rl_clean);
        tvCache = findViewById(R.id.tv_cache);
        rlChargeSet = findViewById(R.id.rl_charge_set);
        tvLogout = findViewById(R.id.tv_logout);

        rlLink.setOnClickListener(this);
        rlUpdate.setOnClickListener(this);
        tvVersion.setOnClickListener(this);
        rlClean.setOnClickListener(this);
        rlChargeSet.setOnClickListener(this);
        findViewById(R.id.rl_feed_back).setOnClickListener(this);
        findViewById(R.id.rl_set_password).setOnClickListener(this);
    }


}
